package cn.jhc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;


/**
 * 登陆过滤器，只有登陆了才能访问某些非公开页面
 */
@WebFilter(filterName="/LoginFilter",urlPatterns="/*")
public class LoginFilter implements Filter {
	private static final Logger LOGGER = Logger.getLogger(LoginFilter.class.getName());
	
    /**
     * Default constructor. 
     */
    public LoginFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		LOGGER.info("login 释放过滤器");
	}

	/**
	 * 过滤器主要函数，过滤逻辑主要写在该这里面
	 * 
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		LOGGER.info("login 过滤器过滤 ");
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		if (isFilter(request)) {
			HttpSession session = request.getSession(false);
			if (session == null || session.getAttribute("username") == null) {
				response.sendRedirect(request.getContextPath() + "/login.jsp");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		LOGGER.info("启动过滤器 login");
	}
	/**
	 * 判断该次访问是否过滤
	 * @param request 页面的HttpServletRequest对象
	 * @return true 过滤 false 不过滤
	 */
	public boolean isFilter(HttpServletRequest request){
		String servletPath = request.getServletPath();
		if (servletPath.startsWith("/user/")) {
			return true;
		}
		return false;
	}
}
